package main
/*
#include <stdio.h>
#include <stdlib.h>
typedef struct {
	char *name;
	int age;
}person;

person* NewPersonArray(int n)
{
	person *pon;
	pon =(person*)malloc(sizeof(person)*n);
	//初始化name
	for(int i = 0; i<n;i++){
	  pon[i].name = (char*)malloc(sizeof(char)*10);
	  pon[i].age = i;
      	  sprintf(pon[i].name, "name:%d", i);
	}
	return pon;
}

void freePersonArray(person* pon, int len)
{
	for (int i = 0; i < len; i ++){
		free(pon[i].name);
	}
	free(pon);
}
*/
import "C"
import (
	"fmt"
	"unsafe"
)

func main() {
	var person *C.person
	n := 10
	person = C.NewPersonArray(C.int(n))  //new一个长度为n的person数组

	//用go的方式遍历C数组
	for i:=0; i < n; i++ {
		p := *(*C.person)(unsafe.Pointer(uintptr(unsafe.Pointer(person)) + uintptr(C.sizeof_person*C.int(i))))
		fmt.Printf("i: %d, p.name: %s, p.age: %d\n", i, C.GoString(p.name), int(p.age) )
	}
	C.freePersonArray(person, C.int(n))
}
